<?php
/**
 * author: draguo
 * Date: 2017/4/27
 */

namespace Admin\Controller;


class ScoreController extends BaseController
{
    public function top()
    {
        $map = $this->getMap();
        $score = D('Score');
        $data=$score->join('user on user.user_id = score_out.user_id')
                    ->field('nickname,score_out.user_id,sum(score) as total')->where($map)
                    ->group('score_out.user_id')->order('total desc')->page($_GET['p'].',20')->select();
        $this->list = $data;
        $count = count($score->field('user_id')->where($map)->group('user_id')->select());
        $Page = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);
        $this->display();
    }

    public function getMap()
    {
        $interval_time = I('get.interval_time');
        if ($interval_time) {
            $time=explode('~',$interval_time);
            $time[0]=$time[0].' 00:00:00';
            $time[1]=$time[1].' 23:59:59';
            $map =' score_out.create_time >"'.$time[0].'" and score_out.create_time < "'.$time[1].'"';
            return $map;
        }
    }

    public function export()
    {
        $data=M('score_out')->join('user on user.user_id = score_out.user_id')
            ->field('nickname,score_out.user_id,count(score) as total')->where($this->getMap())
            ->group('score_out.user_id')->order('total desc')->select();
        $data = $this->format($data);
        $file = excel_export($data);
        ouput_Browser($file);
    }

    private function format($data)
    {
        return array_map(function ($item) {
            return [
                '用户ID' => $item['user_id'],
                '微信昵称' => $item['nickname'],
                '总积分' => $item['total']
            ];
        }, $data);
    }
}